package xyz.coolcsm.security.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.Payload;
import xyz.coolcsm.security.entity.SysRole;
import xyz.coolcsm.security.entity.SysUser;
import xyz.coolcsm.security.utils.JwtUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
 * @author 什锦
 * @since 2021-06-1
 */

public class TokenVerifyFilter extends BasicAuthenticationFilter {

    private RsaKeyProperties prop;

    public TokenVerifyFilter(AuthenticationManager authenticationManager,RsaKeyProperties prop) {
        super(authenticationManager);
        this.prop=prop;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
        //请求体的头中是否包含Authorization
            String header = request.getHeader("Authorization");
        //Authorization中是否包含Bearer，不包含直接返回
            if (header == null || !header.startsWith("Bearer ")) {
                chain.doFilter(request, response);
                return;
            }
        //获取权限失败，会抛出异常
            UsernamePasswordAuthenticationToken authentication = getAuthentication(request,response);;

        //获取后，将Authentication写入SecurityContextHolder中供后序使用
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String token = request.getHeader("Authorization");
        if (token != null) {
          //通过token解析出载荷信息
            Payload<SysUser> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                        prop.getPublicKey(), SysUser.class);
            } catch (ExpiredJwtException e) {
                return null;
            }
            SysUser user = payload.getUserInfo();
            List<SysRole> roles = user.getRoles();
            List<GrantedAuthority> grantedAuthorities  = new ArrayList<>();
            for (int i=0;i<roles.size();i++){
                String role = roles.get(i).getRoleName();
                if(StringUtils.isNotBlank(role)){
                    grantedAuthorities.add(new SimpleGrantedAuthority(role));
                }
            }
            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null,grantedAuthorities);
            }
            return null;
        }
        return null;
    }


}
